#include "InetAddress.hpp"

#include <strings.h>
#include <string.h>

//函数的默认值参数在声明和定义时只能出现一次
InetAddress::InetAddress(uint16_t port,std::string ip)
{
    bzero(&addr_,sizeof addr_);
    addr_.sin_family=AF_INET;
    addr_.sin_port=htons(port); //从主机字节序(小端)转换成网络字节序(大端)
    addr_.sin_addr.s_addr=inet_addr(ip.c_str()); //ipv4点分十进制转换成适合作internet网络地址的祖籍字节顺序中的数字
}

std::string InetAddress::toIp() const
{
    char buf[64]={0};
    ::inet_ntop(AF_INET,&addr_.sin_addr,buf,sizeof buf); // ::显示指定全局作用域
    return buf;
}

std::string InetAddress::toIpPort() const
{
    //ip:port
    char buf[64]={0};
    ::inet_ntop(AF_INET,&addr_.sin_addr,buf,sizeof buf);
    size_t end=strlen(buf);
    uint16_t port=ntohs(addr_.sin_port);
    sprintf(buf+end,":%u",port);
    return buf;
}

uint16_t InetAddress::toPort() const
{
    uint16_t port=ntohs(addr_.sin_port);
    return port;
}

//测试代码
// #include <iostream>
// int main()
// {
//     InetAddress addr(8080);
//     std::cout<<addr.toIp()<<std::endl;
//     std::cout<<addr.toIpPort()<<std::endl;
//     std::cout<<addr.toPort()<<std::endl;
//     return 0;
// }